<?php

namespace App\Http\Controllers\Wap;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Util\Result;
use App\Model\Member;
use App\Model\Receiver;
use Illuminate\Http\Request;

class ReceiverController extends Controller
{

    public function __construct(Request $request){
        $this->request = $request;
//        $this->openid = session('wechat_user')['id'];
        $this->openid = 'oiYTrwfH-VLzRn8OkLsn_knKv3qM';
        if (!empty($this->openid)) {
            $this->memberId = Member::where('openid',$this->openid)->pluck('id');
        }
    }

    /**
     * @return $this
     * 选择地址
     * czs
     */
    public function receiver(){
        $list = Receiver::getMemberReceiver($this->memberId);
        return view('wap.receiver.receiver')->with('list',$list);
    }

    /**
     * @return $this
     * 地址管理
     * czs
     */
    public function index(){
        $list = Receiver::getMemberReceiver($this->memberId);
        return view('wap.receiver.index')->with('list',$list);
    }

    /**
     * @return $this|array
     * 添加收货人
     * czs
     */
    public function add(){
        if($this->request->isMethod('post')) {
            $data = $this->request->all();
            $data['member_id'] = $this->memberId;
            $res = Receiver::addOne($data);
            return $res->getResult();
        } else {
            // 把JSON字符串转成PHP数组
            $json = file_get_contents(public_path('areas.json'));
            $data = json_decode($json, true);
            return view('wap.receiver.add')->with('areas',$data);
        }
    }

    /**
     * @return $this|array
     * 编辑收货人
     * czs
     */
        public function edit($id){
        if($this->request->isMethod('post')) {
            $data = $this->request->all();
            $data['id'] = $id;
            $res = Receiver::updateReceiver($data);
            return $res->getResult();
        } else {
            // 把JSON字符串转成PHP数组
            $json = file_get_contents(public_path('areas.json'));
            $data = json_decode($json, true);
            $one = Receiver::getOne($id);
            return view('wap.receiver.edit')
                ->with('areas',$data)
                ->with('one',$one);
        }
    }

    /**
     * @return array
     * 设为默认收货人
     * czs
     */
    public function setDefault(){
        $id = $this->request->input('id');
        Receiver::setDefault($this->memberId,$id);
        return Result::success()->getResult();
    }


    /**
     * 更换地址
     * czs
     */
    public function confirm() {
        $receiverId = $this->request->input('receiver_id');
        $res = Receiver::changeReceiver($receiverId,$this->memberId);
        return $res->getResult();
    }

    /**
     * @return array
     * 删除收货人
     * czs
     */
    public function delete(){
        $id = $this->request->input('id');
        $res = Receiver::deleteOne($id);
        return $res->getResult();
    }
}
